<?php

namespace Admin\Controller;

use Think\Controller;

class PublicController extends Controller {
		
	public function login() {

		$this->display();
		
	}
	
	public function verify() {

		$config =    array(
			'fontSize'	=>	50,
			'length'	=>	4,
			'useNoise'	=>	true,
			'codeSet'	=>	'0123456789'
		);
	
		$verify = new \Think\Verify($config);
		
		$verify->entry(1);
		
	}
	
	public function checkname() {
		
		$name = I('post.name');
		
		$username = I('post.param');
		
		$m = M('User');
		
		$map['username'] = $username;
		
		$data = $m->where($map)->find();
		
		if($data) {
			
			echo "y";
		 
		}else {
			
			echo "此管理员账号不存在或被禁用";
			
		}
		
	}
	
	public function checklogin(){
		
		if(IS_POST) {
			
			$m = M('User');

			$username = I('post.username');
			
			$password = md5($secure_code . md5(I('post.password')));
			
			$verify = I('post.verify');
			
			if(empty($username)){
				
				echo json_encode(array('info'=>'请输入管理员账号', 'status'=>'n'));
				
			}else if(empty($password)){
				
				echo json_encode(array('info'=>'请输入管理员密码', 'status'=>'n'));
				
			}else if(!check_verify($verify, 1)){

				echo json_encode(array('info'=>'验证码输入错误', 'status'=>'s'));
				
            }else{
			
				$map = array(
					'username'	=>	$username,
					'password'	=>	$password,
					'status'	=>	1,
				);
				
				$admininfo = $m->where($map)->find();
				
				if($admininfo) {
					
					$data = array(
						'last_login_time'	=>	time(),
						'last_login_ip'		=>	get_client_ip(),
						'update_time'		=>	time(),
						'counts'			=>	$admininfo['counts'] + 1,
					);
					
					$uid = $admininfo['id'];
					
					$info = $m->where(array('id'=>$uid))->save($data);
					
					if($info) {
						
						$user = $m->where(array('id'=>$uid))->find();
						
						session(C('AUTH_KEY'), $uid);
						
						session('userinfo', $user);
						
						session('ModelKey.Admin', 1);
						
						echo json_encode(array('info'=>'登录成功', 'status'=>'y'));
						
					}else {
						
						echo json_encode(array('info'=>'用户登录异常', 'status'=>'n'));
						
					}
					
				} else {
					
					echo json_encode(array('info'=>'用户名密码错误或者此用户已被禁用', 'status'=>'n'));
					
				}
			}
			
		} else {
            
			if(UID){
				
                $this->redirect('Index/index');
				
            }else{
				
                $this->redirect('Public/login');
				
            }
        }
    }
	
	public function logout() {
		
		if(!UID) {
			
			$this->error('尚未登录！', U('Admin/Public/login'));
			
		}else{
			
			session(C('AUTH_KEY'), null);
			
			session ('userinfo',null);
			
			session('ModelKey.Admin', null);
			
			if (session(C('AUTH_KEY'))) {
				
				$this->error ( "退出失败", U('Admin/Public/login'));
				
			}else{
				
				$this->redirect('Public/login');
				
			}
		}
				
	}
	
	
}